Introduction to Object-Oriented Programming & C++ Basics
1. Introduction to Programming Paradigms
Programming paradigms are the ways in which we approach solving problems using programming languages. Just like humans have different problem-solving techniques, programming languages offer multiple styles.
Two of the most influential paradigms are:
- Procedural Programming
- Object-Oriented Programming (OOP)
1.1 Procedural Programming
Procedural programming, also called imperative programming, is like writing a recipe. Each step must be followed in sequence.
Key Features:
- Step-by-step instructions.
- Functions/procedures handle specific tasks.
- Data is manipulated by these functions.
- Flow of control is achieved using loops, conditions, and functions.
Example – Procedural style C++ code:
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int x = 5, y = 10;
int result = add(x, y);
cout << "Sum: " << result << endl;
return 0;
}
Output:
Sum: 15
Here, the focus is on functions (like add) rather than on objects.
✅ Strengths: Easy to learn, good for small programs.
❌ Weaknesses: Hard to maintain and scale for large systems.
1.2 Object-Oriented Programming (OOP)
Object-oriented programming is inspired by the real world. Instead of writing everything in steps, we model the problem as objects with attributes (data) and behaviors (methods).
Example – OOP style C++ code:
#include <iostream>
using namespace std;
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};
int main() {
Calculator calc;
cout << "Sum: " << calc.add(5, 10) << endl;
return 0;
}
Output:
Sum: 15
Here, Calculator is an object that makes the design closer to real-life modeling.
✅ Strengths: Scalable, reusable, secure.
❌ Weaknesses: Slightly more complex to learn initially.
📝 Practice Exercise
Write a simple procedural program in C++ that calculates the factorial of a number.
Redesign the same program using OOP principles (create a Factorial class).
2. Features and Benefits of OOP
OOP is built on four fundamental pillars:
- Encapsulation – Wrapping data and functions together.
- Abstraction – Showing only necessary details.
- Inheritance – Reusing code through class hierarchy.
- Polymorphism – One function/method behaving differently in different contexts.
2.1 Encapsulation
Imagine a capsule medicine: the ingredients are hidden inside, and you just consume the capsule. Similarly, in C++, class hides the internal details.
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance; // private data
public:
BankAccount(double initial) {
balance = initial;
}
void deposit(double amount) {
balance += amount;
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount acc(1000);
acc.deposit(500);
cout << "Balance: " << acc.getBalance() << endl;
return 0;
}
Output:
Balance: 1500
2.2 Abstraction
We don’t need to know how a car engine works to drive a car. Abstraction hides complexity.
In C++, abstract classes and interfaces achieve this.
2.3 Inheritance
Inheritance allows one class to derive from another.
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal {
public:
void bark() { cout << "Barking..." << endl; }
};
int main() {
Dog d;
d.eat();
d.bark();
}
Output:
Eating...
Barking...
2.4 Polymorphism
Polymorphism means “many forms.”
- Function Overloading – Same function name, different parameters.
- Operator Overloading – Redefining operators.
- Runtime Polymorphism – Achieved using virtual functions.
📝 Practice Exercise
Create a Shape base class and derive Circle and Rectangle classes. Write a function to calculate area (using polymorphism).
Demonstrate encapsulation by designing a Student class with private data members.
3. Basics of C++ Programming
Now that we understand OOP concepts, let’s step into C++ basics.
3.1 Program Structure
#include <iostream>
using namespace std;
int main() {
cout << "Hello C++ World!" << endl;
return 0;
}
3.2 Data Types
C++ has:
- Primitive types: int, char, float, double, bool.
- Derived types: arrays, pointers, references.
- User-defined: structures, classes.
3.3 Variables and Constants
int age = 25;
const float PI = 3.14;
3.4 Operators
int a = 10, b = 20;
cout << "Sum = " << a + b;
3.5 Input and Output
int x;
cout << "Enter a number: ";
cin >> x;
cout << "You entered " << x;
📝 Practice Exercise
Write a program to swap two numbers using a third variable.
Write a program to calculate the area of a circle (use const PI).
4. Control Structures in C++
4.1 Decision-Making
if, if-else, if-else-if, switch.
4.2 Looping
for, while, do-while.
Example:
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
Output:
1 2 3 4 5
📝 Practice Exercise
Write a program to print all even numbers from 1 to 50.
Write a program that takes marks as input and assigns grades using if-else.
5. Functions in C++
5.1 Declaration & Definition
int add(int a, int b) { return a + b; }
5.2 Function Overloading
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
5.3 Inline Functions
inline int square(int x) { return x * x; }
5.4 Recursion
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
📝 Practice Exercise
Write a recursive function to calculate Fibonacci numbers.
Demonstrate function overloading with two multiply functions.
6. Conclusion
We explored:
- Programming paradigms (Procedural vs OOP).
- Four pillars of OOP.
- C++ basics (syntax, data types, variables, operators, I/O).
- Control structures (decision-making & loops).
- Functions (declaration, overloading, recursion, inline).
C++ is not just a programming language—it is a bridge between procedural and object-oriented styles. With this strong foundation, you can now explore classes, objects, inheritance, polymorphism, and advanced topics like file handling, templates, and the Standard Template Library (STL).
Activity 1: Write a C++ program using basic syntax, cin, and cout
Problem Statement:
Write a program that takes the user’s name and age as input and then displays them using cin and cout.
Program:
#include <iostream>
using namespace std;
int main() {
string name;
int age;
// Input
cout << "Enter your name: ";
cin >> name;
cout << "Enter your age: ";
cin >> age;
// Output
cout << "Hello " << name << "! You are " << age << " years old." << endl;
return 0;
}
Sample Output:
Enter your name: Vivek
Enter your age: 25
Hello Vivek! You are 25 years old.
Activity 2: Demonstrate looping constructs with nested loops
Problem Statement:
Write a program to print a multiplication table (1 to 5) using nested loops.
Program:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
cout << i * j << "\t";
}
cout << endl; // Move to next line after inner loop
}
return 0;
}
Sample Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Activity 3: Create a recursive function to calculate the factorial or the Fibonacci series
(a) Factorial using Recursion
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Factorial of " << num << " = " << factorial(num) << endl;
return 0;
}
Sample Output:
Enter a number: 5
Factorial of 5 = 120
(b) Fibonacci using Recursion
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int terms;
cout << "Enter number of terms: ";
cin >> terms;
cout << "Fibonacci Series: ";
for (int i = 0; i < terms; i++) {
cout << fibonacci(i) << " ";
}
cout << endl;
return 0;
}
Sample Output:
Enter number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8
Activity 4: Implement a simple C++ program with function overloading
Problem Statement:
Write a program that overloads the add function to work with both integers and floating-point numbers.
Program:
#include <iostream>
using namespace std;
// Function overloading
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int main() {
cout << "Sum of integers: " << add(5, 10) << endl;
cout << "Sum of doubles: " << add(3.5, 2.7) << endl;
return 0;
}
Sample Output:
Sum of integers: 15
Sum of doubles: 6.2
Comments
Post a Comment